import 'package:flutter/material.dart';
import 'package:event_bus/event_bus.dart';

// 初始化事件总线
EventBus eventBus = EventBus();

// 自定义事件类
class CustomEvent {
  final String message;
  CustomEvent(this.message);
}

void main() {
  runApp(const EventHandlingApp());
}

class EventHandlingApp extends StatelessWidget {
  const EventHandlingApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter 事件与通知',
      theme: ThemeData(primarySwatch: Colors.blue, useMaterial3: true),
      home: const EventHandlingHomePage(),
      debugShowCheckedModeBanner: false,
    );
  }
}

class EventHandlingHomePage extends StatefulWidget {
  const EventHandlingHomePage({super.key});

  @override
  State<EventHandlingHomePage> createState() => _EventHandlingHomePageState();
}

class _EventHandlingHomePageState extends State<EventHandlingHomePage> {
  final ScrollController _scrollController = ScrollController();
  int _currentIndex = 0;
  String _pointerStatus = '无事件';
  String _gestureStatus = '无手势';
  String _notificationStatus = '无通知';
  String _eventBusStatus = '无事件';
  double _rotation = 0.0;
  double _scale = 1.0;
  bool _ignorePointer = false;
  bool _absorbPointer = false;
  bool _showHitTestOverlay = false;
  Offset _position = Offset.zero;

  @override
  void initState() {
    super.initState();
    // 监听事件总线
    eventBus.on<CustomEvent>().listen((event) {
      setState(() {
        _eventBusStatus = '收到事件: ${event.message}';
      });
    });
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('事件处理与通知机制'),
        actions: [
          IconButton(
            icon: const Icon(Icons.info),
            onPressed: () => _showInfoDialog(context),
          ),
        ],
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 8.1 原始指针事件处理
            _buildSectionTitle('8.1 原始指针事件处理'),

            // 8.1.1 命中测试简介
            _buildSubtitle('8.1.1 命中测试简介'),
            _buildHitTestDemo(),

            const SizedBox(height: 20),

            // 8.1.2 Listener组件
            _buildSubtitle('8.1.2 Listener组件'),
            _buildListenerDemo(),

            const SizedBox(height: 20),

            // 8.1.3 忽略指针事件
            _buildSubtitle('8.1.3 忽略指针事件'),
            _buildIgnorePointerDemo(),

            const Divider(height: 40),

            // 8.2 手势识别
            _buildSectionTitle('8.2 手势识别'),
            _buildGestureDetectorDemo(),

            const Divider(height: 40),

            // 8.3 Flutter事件机制
            _buildSectionTitle('8.3 Flutter事件机制'),
            _buildEventFlowDemo(),

            const Divider(height: 40),

            // 8.4 手势原理与手势冲突
            _buildSectionTitle('8.4 手势原理与手势冲突'),
            _buildGestureConflictDemo(),

            const Divider(height: 40),

            // 8.5 事件总线
            _buildSectionTitle('8.5 事件总线'),
            _buildEventBusDemo(),

            const Divider(height: 40),

            // 8.6 通知Notification
            _buildSectionTitle('8.6 通知Notification'),
            _buildNotificationDemo(),

            const SizedBox(height: 40),
          ],
        ),
      ),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        onTap: (index) => setState(() => _currentIndex = index),
        items: const [
          BottomNavigationBarItem(icon: Icon(Icons.touch_app), label: '指针'),
          BottomNavigationBarItem(icon: Icon(Icons.gesture), label: '手势'),
          BottomNavigationBarItem(icon: Icon(Icons.notifications), label: '通知'),
        ],
      ),
    );
  }

  Widget _buildSectionTitle(String title) {
    return Text(
      title,
      style: const TextStyle(
        fontSize: 20,
        fontWeight: FontWeight.bold,
        color: Colors.blue,
      ),
    );
  }

  Widget _buildSubtitle(String title) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: Text(
        title,
        style: const TextStyle(
          fontSize: 16,
          fontWeight: FontWeight.w600,
          color: Colors.blueGrey,
        ),
      ),
    );
  }

  // 8.1.1 命中测试简介
  Widget _buildHitTestDemo() {
    return Column(
      children: [
        const Text('命中测试决定哪个组件处理事件，从子组件向上进行'),
        const SizedBox(height: 10),

        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            ElevatedButton(
              onPressed:
                  () => setState(
                    () => _showHitTestOverlay = !_showHitTestOverlay,
                  ),
              child: Text(_showHitTestOverlay ? '隐藏覆盖层' : '显示覆盖层'),
            ),
            Text('状态: ${_showHitTestOverlay ? '覆盖层可见' : '覆盖层隐藏'}'),
          ],
        ),

        const SizedBox(height: 10),

        Stack(
          children: [
            Container(
              width: double.infinity,
              height: 150,
              color: Colors.blue.shade100,
              child: const Center(child: Text('底层组件')),
            ),
            if (_showHitTestOverlay)
              Positioned(
                top: 30,
                left: 50,
                child: Listener(
                  onPointerDown: (e) => print('覆盖层点击'),
                  child: Container(
                    width: 200,
                    height: 100,
                    color: Colors.red.withOpacity(0.5),
                    child: const Center(child: Text('覆盖层 (命中测试优先)')),
                  ),
                ),
              ),
          ],
        ),

        const SizedBox(height: 10),
        const Text('覆盖层组件会优先处理事件，阻止事件传递到底层'),
      ],
    );
  }

  // 8.1.2 Listener组件
  Widget _buildListenerDemo() {
    return Column(
      children: [
        Text('指针状态: $_pointerStatus', style: const TextStyle(fontSize: 16)),
        const SizedBox(height: 10),

        Listener(
          onPointerDown:
              (e) => setState(() => _pointerStatus = '按下: ${e.position}'),
          onPointerMove:
              (e) => setState(() => _pointerStatus = '移动: ${e.position}'),
          onPointerUp:
              (e) => setState(() => _pointerStatus = '抬起: ${e.position}'),
          onPointerCancel: (e) => setState(() => _pointerStatus = '取消'),
          child: Container(
            width: double.infinity,
            height: 120,
            decoration: BoxDecoration(
              color: Colors.amber.shade200,
              borderRadius: BorderRadius.circular(12),
            ),
            child: const Center(
              child: Text('在此区域移动/点击指针', style: TextStyle(fontSize: 18)),
            ),
          ),
        ),

        const SizedBox(height: 10),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            ElevatedButton(
              onPressed: () => setState(() => _pointerStatus = '已重置'),
              child: const Text('重置状态'),
            ),
            ElevatedButton(
              onPressed:
                  () => setState(() {
                    _rotation = 0.0;
                    _scale = 1.0;
                    _position = Offset.zero;
                  }),
              child: const Text('重置变换'),
            ),
          ],
        ),
      ],
    );
  }

  // 8.1.3 忽略指针事件
  Widget _buildIgnorePointerDemo() {
    return Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            Switch(
              value: _ignorePointer,
              onChanged: (v) => setState(() => _ignorePointer = v),
            ),
            Text('IgnorePointer: ${_ignorePointer ? '开启' : '关闭'}'),

            Switch(
              value: _absorbPointer,
              onChanged: (v) => setState(() => _absorbPointer = v),
            ),
            Text('AbsorbPointer: ${_absorbPointer ? '开启' : '关闭'}'),
          ],
        ),

        const SizedBox(height: 10),

        IgnorePointer(
          ignoring: _ignorePointer,
          child: AbsorbPointer(
            absorbing: _absorbPointer,
            child: Container(
              width: double.infinity,
              height: 100,
              decoration: BoxDecoration(
                color:
                    _ignorePointer
                        ? Colors.grey
                        : _absorbPointer
                        ? Colors.red.shade200
                        : Colors.green.shade200,
                borderRadius: BorderRadius.circular(10),
              ),
              child: Center(
                child: Text(
                  _ignorePointer
                      ? '忽略事件 (事件穿透)'
                      : _absorbPointer
                      ? '吸收事件 (阻止传递)'
                      : '正常事件处理',
                  style: const TextStyle(fontSize: 18),
                ),
              ),
            ),
          ),
        ),

        const SizedBox(height: 10),
        const Text('IgnorePointer: 忽略事件，允许事件穿透到下层'),
        const Text('AbsorbPointer: 吸收事件，阻止事件传递到下层'),
      ],
    );
  }

  // 8.2 手势识别 - 修复了手势冲突问题
  Widget _buildGestureDetectorDemo() {
    return Column(
      children: [
        Text('手势状态: $_gestureStatus', style: const TextStyle(fontSize: 16)),
        const SizedBox(height: 10),

        GestureDetector(
          onTap: () => setState(() => _gestureStatus = '点击'),
          onDoubleTap: () => setState(() => _gestureStatus = '双击'),
          onLongPress: () => setState(() => _gestureStatus = '长按'),
          // 移除了 onPanUpdate，使用 onScaleUpdate 处理所有变换
          onScaleUpdate: (d) {
            setState(() {
              // 处理平移
              _position += d.focalPointDelta;

              // 处理旋转和缩放
              _rotation += d.rotation;
              _scale *= d.scale;

              // 更新状态显示
              _gestureStatus =
                  '位置: (${_position.dx.toStringAsFixed(1)}, ${_position.dy.toStringAsFixed(1)})\n'
                  '缩放: ${_scale.toStringAsFixed(2)}\n'
                  '旋转: ${_rotation.toStringAsFixed(2)}';
            });
          },
          child: Transform.translate(
            offset: _position,
            child: Transform.rotate(
              angle: _rotation,
              child: Transform.scale(
                scale: _scale,
                child: Container(
                  width: 200,
                  height: 150,
                  decoration: BoxDecoration(
                    color: Colors.purple.shade200,
                    borderRadius: BorderRadius.circular(15),
                  ),
                  child: const Center(
                    child: Text(
                      '手势识别区域\n(点击/双击/长按/平移/缩放/旋转)',
                      textAlign: TextAlign.center,
                      style: TextStyle(fontSize: 16),
                    ),
                  ),
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  // 8.3 Flutter事件机制
  Widget _buildEventFlowDemo() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          'Flutter事件处理流程:',
          style: TextStyle(fontWeight: FontWeight.bold),
        ),
        const SizedBox(height: 10),
        _buildEventFlowStep('1. 原始指针事件', Colors.blue.shade100),
        _buildEventFlowStep('2. 手势识别器处理', Colors.green.shade100),
        _buildEventFlowStep('3. 组件事件处理', Colors.amber.shade100),
        _buildEventFlowStep('4. 路由事件处理', Colors.purple.shade100),
        _buildEventFlowStep('5. 全局事件处理', Colors.red.shade100),
        const SizedBox(height: 10),
        const Text('事件从最内层组件向外层传递，直到被处理'),
      ],
    );
  }

  Widget _buildEventFlowStep(String text, Color color) {
    return Container(
      width: double.infinity,
      margin: const EdgeInsets.symmetric(vertical: 5),
      padding: const EdgeInsets.all(10),
      decoration: BoxDecoration(
        color: color,
        borderRadius: BorderRadius.circular(8),
      ),
      child: Text(text),
    );
  }

  // 8.4 手势原理与手势冲突
  Widget _buildGestureConflictDemo() {
    return Column(
      children: [
        const Text(
          '手势冲突示例: 拖动与点击',
          style: TextStyle(fontWeight: FontWeight.bold),
        ),
        const SizedBox(height: 10),

        Row(
          children: [
            Expanded(
              child: GestureDetector(
                onTap: () => setState(() => _gestureStatus = '左侧区域点击'),
                child: Container(
                  height: 100,
                  color: Colors.blue.shade200,
                  child: const Center(child: Text('点击区域')),
                ),
              ),
            ),
            const SizedBox(width: 10),
            Expanded(
              child: GestureDetector(
                onPanUpdate: (d) => setState(() => _gestureStatus = '右侧区域拖动: ${d.delta}'),
                child: Container(
                  height: 100,
                  color: Colors.green.shade200,
                  child: const Center(child: Text('拖动区域')),
                ),
              ),
            ),
          ],
        ),

        const SizedBox(height: 10),
        const Text('左侧: 只响应点击'),
        const Text('右侧: 只响应拖动'),
        const SizedBox(height: 10),
        const Text('解决冲突方法:'),
        const Text('1. 分离手势识别区域'),
        const Text('2. 使用不同手势识别器'),
        const Text('3. 使用Listener处理原始指针事件'),
      ],
    );
  }

  // 8.5 事件总线
  Widget _buildEventBusDemo() {
    return Column(
      children: [
        Text('事件总线状态: $_eventBusStatus', style: const TextStyle(fontSize: 16)),
        const SizedBox(height: 10),

        Wrap(
          spacing: 10,
          runSpacing: 10,
          children: [
            ElevatedButton(
              onPressed: () => eventBus.fire(CustomEvent('事件1')),
              child: const Text('发送事件1'),
            ),
            ElevatedButton(
              onPressed: () => eventBus.fire(CustomEvent('事件2')),
              child: const Text('发送事件2'),
            ),
            ElevatedButton(
              onPressed: () => eventBus.fire(CustomEvent('登录成功')),
              child: const Text('发送登录事件'),
            ),
            ElevatedButton(
              onPressed: () => eventBus.fire(CustomEvent('数据更新')),
              child: const Text('发送数据事件'),
            ),
          ],
        ),

        const SizedBox(height: 20),
        const Text('事件总线用于组件间通信，尤其是不直接关联的组件'),
      ],
    );
  }

  // 8.6 通知Notification
  Widget _buildNotificationDemo() {
    return Column(
      children: [
        Text(
          '通知状态: $_notificationStatus',
          style: const TextStyle(fontSize: 16),
        ),
        const SizedBox(height: 10),

        ElevatedButton(
          onPressed: () {
            const CustomNotification(message: '自定义通知').dispatch(context);
          },
          child: const Text('发送自定义通知'),
        ),

        const SizedBox(height: 20),

        Container(
          height: 200,
          decoration: BoxDecoration(
            border: Border.all(color: Colors.grey),
            borderRadius: BorderRadius.circular(10),
          ),
          child: NotificationListener<ScrollNotification>(
            onNotification: (notification) {
              if (notification is ScrollStartNotification) {
                setState(() => _notificationStatus = '滚动开始');
              } else if (notification is ScrollUpdateNotification) {
                setState(
                  () =>
                      _notificationStatus = '滚动更新: ${notification.scrollDelta}',
                );
              } else if (notification is ScrollEndNotification) {
                setState(() => _notificationStatus = '滚动结束');
              }
              return true; // 阻止继续向上传递
            },
            child: ListView.builder(
              controller: _scrollController,
              itemCount: 30,
              itemBuilder: (context, index) {
                return ListTile(title: Text('项目 $index'));
              },
            ),
          ),
        ),

        const SizedBox(height: 10),
        const Text('通知机制用于从子组件向父组件传递信息'),
      ],
    );
  }

  void _showInfoDialog(BuildContext context) {
    showDialog(
      context: context,
      builder:
          (context) => AlertDialog(
            title: const Text('事件处理与通知机制'),
            content: const SingleChildScrollView(
              child: Text(
                '本应用展示了Flutter中的事件处理与通知机制:\n\n'
                '1. 原始指针事件处理: 使用Listener监听原始指针事件\n'
                '2. 手势识别: 使用GestureDetector识别各种手势\n'
                '3. 事件机制: Flutter的事件传递流程\n'
                '4. 手势冲突: 手势识别冲突及解决方案\n'
                '5. 事件总线: 使用event_bus实现组件间通信\n'
                '6. 通知机制: 使用NotificationListener监听通知',
              ),
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context),
                child: const Text('确定'),
              ),
            ],
          ),
    );
  }
}

// 自定义通知类
class CustomNotification extends Notification {
  final String message;
  const CustomNotification({required this.message});
}
